package com.huang.oauth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huang.oauth.constant.OauthConstant;
import com.huang.oauth.domain.SysUser;
import com.huang.oauth.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author hqy
 * @date 2022年06月20日 14:37
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String loginType = request.getHeader("loginType");

        switch (loginType){
            //后台管理员  查询 进行权限的封装
            case OauthConstant.LOGIN_TYPE_SYS:
                SysUser sysUser  = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, username)
                        .select(SysUser::getUsername, SysUser::getPassword, SysUser::getStatus, SysUser::getUserId));
                Assert.notNull(sysUser,"暂时没有此用户哦！！！！！");

                List<String> perms =  sysUserMapper.loadPerms(sysUser.getUserId());
                sysUser.setAuths(perms);
                return sysUser;

                //前台用户   微信小程序
            case OauthConstant.LOGIN_TYPE_USER:
                return null;
            default:
                return null;
        }

    }
}
